package com.snlab;

import java.math.BigInteger;

import jdd.bdd.BDD;

public class BDDEngine {
    public BDD bdd;
    private int[] vars;

    public BDDEngine() {
        this.bdd = new BDD(1000, 10000);
        this.vars = new int[32];
        for (int i = 0; i < 32; i++) {
            vars[i] = bdd.createVar();
        }
    }

    public int encodeIpv4(BigInteger ip, int prefix) {
        int result = 1;
        for (int i = 0; i < prefix; i++) {
            if (ip.testBit(31 - i)) {
                int tmp = bdd.ref(bdd.and(result, vars[i]));
                bdd.deref(result);
                result = tmp;
            } else {
                int tmp = bdd.ref(bdd.not(vars[i]));
                int tmp1 = bdd.ref(bdd.and(result, tmp));
                bdd.deref(tmp);
                bdd.deref(result);
                result = tmp1;
            }
        }
        return result;
    }

    public int encodeIpv4(long ip, int prefix) {
        return encodeIpv4(BigInteger.valueOf(ip), prefix);
    }
}
